﻿using System;
using System.Linq;
using System.Windows.Data;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;

namespace ForumsBrowser
{
    public static class StarPointsGenerator
    {
        public static PointCollection Generate(double radius, int numberOfPoints)
        {
            return GetStarPoints(numberOfPoints, radius);
        }

        private static PointCollection GetStarPoints(int pointcount, double radius)
        {
            PointCollection collection = new PointCollection();

            var outer = OuterPoints(5, radius / 2).ToList();
            var inner = GetInnerPoints(outer).ToList();
            for (int i = 0; i < outer.Count; i++)
            {
                collection.Add(outer[i]);
                collection.Add(inner[i]);
            }
            return collection;
        }

        private static IEnumerable<Point> OuterPoints(int pointcount, double radius)
        {
            float angle = (float)360 / pointcount;
            for (int i = 0; i < pointcount; i++)
            {
                yield return GetCircumferencePoints(radius, radius, radius, angle * (double)i);
            }
        }

        private static Point GetCircumferencePoints(double Radius, double OriginX, double OriginY, double Angle)
        {
            var X = OriginX + Radius * Math.Sin(Angle * Math.PI / 180);
            var Y = OriginY + Radius * -Math.Cos(Angle * Math.PI / 180);
            return new Point(X, Y);
        }

        private static IEnumerable<Point> GetInnerPoints(List<Point> points)
        {
            int[] modifiers = { -1, 0, 1, 2 };
            for (int i = 0; i < points.Count; i++)
            {
                var cpoints = modifiers.Select(m => points[(i + points.Count + m) % points.Count]).ToArray();
                yield return FindIntersection(cpoints[0], cpoints[2], cpoints[1], cpoints[3]);
            }
        }

        private static Point FindIntersection(Point p1, Point p2, Point p3, Point p4)
        {
            double m1 = (p2.Y - p1.Y) / (p2.X - p1.X);
            double m2 = (p4.Y - p3.Y) / (p4.X - p3.X);

            double b1 = p1.Y - (m1 * p1.X);
            double b2 = p3.Y - (m2 * p3.X);

            double x_intersect = (b2 - b1) / (m1 - m2);
            double y_intersect = (m1 * x_intersect) + b1;

            return new Point(x_intersect, y_intersect);
        }
    }
}
